package com.dcy.file.biz.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.dcy.db.base.service.BaseService;
import com.dcy.file.biz.mapper.FileInfoMapper;
import com.dcy.file.biz.model.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2019/12/17 9:03
 */
@Service
public class FileInfoService extends BaseService<FileInfoMapper, FileInfo> {

    @Autowired
    private IFileHandler iFileHandler;

    private static final String FILE_SPLIT = ".";

    public FileInfo upload(MultipartFile file) throws Exception {
        return uploadCommonFile(file);
    }

    private FileInfo uploadCommonFile(MultipartFile file) throws Exception {
        FileInfo fileInfo = new FileInfo()
                .setName(file.getOriginalFilename())
                .setContentType(file.getContentType())
                .setFileSize(file.getSize())
                .setCreateDate(new Date());
        if (!fileInfo.getName().contains(FILE_SPLIT)) {
            throw new IllegalArgumentException("缺少后缀名");
        }
        iFileHandler.uploadFile(file, fileInfo);
        // 设置文件来源
        fileInfo.setSource(iFileHandler.fileType());
        // 将文件信息保存到数据库
        save(fileInfo);
        return fileInfo;
    }

    public void deleteFile(String id) {
        FileInfo fileInfo = getById(id);
        if (fileInfo != null) {
            removeById(fileInfo.getId());
            iFileHandler.deleteFile(fileInfo);
        }
    }

    public List<FileInfo> uploadFiles(MultipartFile[] files) {
        List<FileInfo> fileInfos = new ArrayList<>();
        Arrays.asList(files).stream().forEach(multipartFile -> {
            try {
                FileInfo fileInfo = uploadCommonFile(multipartFile);
                fileInfos.add(fileInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return fileInfos;
    }

    public void downLoad(String fileName, String filePath, HttpServletResponse response) {
        if (StrUtil.isNotBlank(fileName) && StrUtil.isNotBlank(filePath)) {
            iFileHandler.downLoadFile(fileName, filePath, response);
        }
    }

}
